package cn.wolfcode.web.controller;


import cn.wolfcode.domain.Business;
import cn.wolfcode.qo.BusinessQueryObject;
import cn.wolfcode.service.IBusinessService;
import cn.wolfcode.qo.JsonResult;
import cn.wolfcode.util.FileUploadUtil;
import cn.wolfcode.util.RequiredPermission;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletContext;
import java.util.List;

@Controller
@RequestMapping("/business")
public class BusinessController {

    @Autowired
    private IBusinessService businessService;
    @Autowired
    private ServletContext servletContext;

    @RequiredPermission(name = "门店页面", expression = "business:list")
    @RequestMapping("/list")
    public String list(Model model, @ModelAttribute("qo") BusinessQueryObject qo){
        PageInfo<Business> pageInfo = businessService.query(qo);
        model.addAttribute("pageInfo", pageInfo);
        return "business/list";
    }

    @RequiredPermission(name = "门店页面", expression = "business:delete")
    @RequestMapping("/delete")
    @ResponseBody
    public JsonResult delete(Long id){
        if (id != null) {
            businessService.delete(id);
        }
        return new JsonResult();
    }


    @RequestMapping("/saveOrUpdate")
    @RequiredPermission(name = "门店页面", expression = "business:saveOrUpdate")
    public String saveOrUpdate(Business business, MultipartFile file) throws Exception {
        if (file != null && file.getSize() > 0) {
            String realPath = servletContext.getRealPath("/");
            if (StringUtils.hasText(business.getLicenseImg())) {
                FileUploadUtil.deleteFile(realPath + business.getLicenseImg());
            }
            String uploadFile = FileUploadUtil.uploadFile(file, realPath);
            business.setLicenseImg(uploadFile);
        }

        if (business.getId() != null) {
            businessService.update(business);
        }else {
            businessService.save(business);
        }
        return "redirect:/business/list";
    }

    // 处理去保存或修改请求 /business/input
    @RequiredPermission(name="门店新增/编辑", expression = "business:saveOrUpdate")
    @RequestMapping("/input")
    public String input(Long id, Model model) {
        if (id != null) {
            model.addAttribute("business", businessService.get(id));
        }
        return "business/input";
    }

    @RequestMapping("/listAll")
    @ResponseBody
    public List<Business> listAll() {
        return businessService.listAll();
    }
}
